<template>
  <view class="fu-form">
    <slot></slot>
  </view>
</template>

<script>
/**
 * fu-form 表单组件
 * @description 表单组件，用于数据录入、校验
 * @property {Object} model - 表单数据对象
 * @property {Object} rules - 表单验证规则
 * @property {String} labelPosition - 标签位置，可选值：left/top
 * @property {String} labelWidth - 标签宽度，默认单位rpx
 * @property {Boolean} hideRequiredAsterisk - 是否隐藏必填字段的标签旁边的红色星号
 * @event {Function} validate - 对整个表单进行校验的方法
 */
export default {
  name: 'fu-form',
  props: {
    model: {
      type: Object,
      default: () => ({})
    },
    rules: {
      type: Object,
      default: () => ({})
    },
    labelPosition: {
      type: String,
      default: 'left',
      validator: value => ['left', 'top'].includes(value)
    },
    labelWidth: {
      type: String,
      default: '180rpx'
    },
    hideRequiredAsterisk: {
      type: Boolean,
      default: false
    }
  },
  provide() {
    return {
      form: this
    }
  },
  data() {
    return {
      fields: []
    }
  },
  methods: {
    addField(field) {
      if (field) {
        this.fields.push(field)
      }
    },
    removeField(field) {
      if (field) {
        this.fields = this.fields.filter(item => item !== field)
      }
    },
    validate(callback) {
      let valid = true
      let count = 0
      const fields = this.fields

      if (fields.length === 0 && callback) {
        callback(true)
      }

      fields.forEach(field => {
        field.validate('', errors => {
          if (errors) {
            valid = false
          }
          if (++count === fields.length && callback) {
            callback(valid)
          }
        })
      })
    },
    resetFields() {
      this.fields.forEach(field => {
        field.resetField()
      })
    },
    clearValidate(props = []) {
      const fields = props.length
        ? typeof props === 'string'
          ? this.fields.filter(field => props === field.prop)
          : this.fields.filter(field => props.indexOf(field.prop) > -1)
        : this.fields
      fields.forEach(field => {
        field.clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.fu-form {
  width: 100%;
}
</style> 